/**
 * @file
 * @author dousha 
 * @date 2021/4/23.
 */

#include "i2c_bus.h"
#include "stm32f1xx_hal.h"

void i2c_write_reg(I2C_HandleTypeDef *hwnd, uint8_t addr, uint8_t reg, uint8_t value) {
	uint8_t buf[2] = {reg, value};
	HAL_I2C_Master_Transmit(hwnd, addr << 1u, buf, 2, HAL_MAX_DELAY);
}

uint8_t i2c_read_reg(I2C_HandleTypeDef *hwnd, uint8_t addr, uint8_t reg) {
	uint8_t buf = 0;
	HAL_I2C_Master_Transmit(hwnd, addr << 1u, &reg, 1, HAL_MAX_DELAY);
	HAL_I2C_Master_Receive(hwnd, addr << 1u, &buf, 1, HAL_MAX_DELAY);
	return buf;
}

uint16_t i2c_read_reg_16le(I2C_HandleTypeDef *hwnd, uint8_t addr, uint8_t reg) {
	uint8_t buf[2] = {reg, 0};
	HAL_I2C_Master_Transmit(hwnd, addr << 1u, buf, 1, HAL_MAX_DELAY);
	HAL_I2C_Master_Receive(hwnd, addr << 1u, buf, 2, HAL_MAX_DELAY);
	return (buf[1] << 8) | buf[0];
}

uint16_t i2c_read_reg_16be(I2C_HandleTypeDef *hwnd, uint8_t addr, uint8_t reg) {
	uint8_t buf[2] = {reg, 0};
	HAL_I2C_Master_Transmit(hwnd, addr << 1u, buf, 1, HAL_MAX_DELAY);
	HAL_I2C_Master_Receive(hwnd, addr << 1u, buf, 2, HAL_MAX_DELAY);
	return (buf[0] << 8) | buf[1];
}

int16_t i2c_read_reg_s16le(I2C_HandleTypeDef *hwnd, uint8_t addr, uint8_t reg) {
	return (int16_t) i2c_read_reg_16le(hwnd, addr, reg);
}

int16_t i2c_read_reg_s16be(I2C_HandleTypeDef *hwnd, uint8_t addr, uint8_t reg) {
	return (int16_t) i2c_read_reg_16be(hwnd, addr, reg);
}

void i2c_read(I2C_HandleTypeDef *hwnd, uint8_t addr, uint8_t reg, uint8_t *in, uint32_t len) {
	HAL_I2C_Master_Transmit(hwnd, addr << 1u, &reg, 1, HAL_MAX_DELAY);
	HAL_I2C_Master_Receive(hwnd, addr << 1u, in, len, HAL_MAX_DELAY);
}
